package com.ruoyi.ldzlsb.controller;

import java.util.List;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.ldzlsb.domain.SbRepairApplication;
import com.ruoyi.ldzlsb.service.ISbRepairApplicationService;
import com.ruoyi.ldzlsb.domain.vo.SbEquipmentVo;
import com.ruoyi.ldzlsb.service.ISbEquipmentService;
import com.ruoyi.ldzlsb.domain.SbRepairOrder;
import com.ruoyi.ldzlsb.service.ISbRepairOrderService;
import com.ruoyi.common.core.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 设备报修单Controller
 * 
 * @author ruoyi
 * @date 2025-07-22
 */
@RestController
@RequestMapping("/sb/repair/application")
public class SbRepairApplicationController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(SbRepairApplicationController.class);
    
    @Autowired
    private ISbRepairApplicationService repairApplicationService;
    
    @Autowired
    private ISbEquipmentService equipmentService;

    /**
     * 查询设备报修单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SbRepairApplication application)
    {
        startPage();
        List<SbRepairApplication> list = repairApplicationService.findRepairApplication(application);
        return getDataTable(list);
    }
    
    /**
     * 获取可用设备列表，用于报修单选择设备
     */
    @GetMapping("/equipment/list")
    public TableDataInfo getEquipmentList()
    {
        try {
            SbEquipmentVo query = new SbEquipmentVo();
            // 只查询状态为正常的设备
            query.setEquipmentStatus("0"); 
            startPage();
            List<SbEquipmentVo> list = equipmentService.selectSbEquipmentList(query);
            return getDataTable(list);
        } catch (Exception e) {
            log.error("获取设备列表失败", e);
            return getDataTable(new ArrayList<>());
        }
    }

    /**
     * 获取设备报修单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        try {
            SbRepairApplication application = repairApplicationService.getById(id);
            return success(application);
        } catch (Exception e) {
            log.error("获取报修单详情失败", e);
            return error("获取报修单详情失败: " + e.getMessage());
        }
    }

    /**
     * 新增设备报修单
     */
    @Log(title = "设备报修单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbRepairApplication application)
    {
        try {
            // 记录完整的请求数据，便于调试
            log.info("接收到的报修单数据: {}", application);
            
            // 参数验证
            if (application.getEquipmentId() == null) {
                log.warn("设备ID为空");
                return AjaxResult.error("设备ID不能为空");
            }
            if (application.getReportPerson() == null || application.getReportPerson().isEmpty()) {
                log.warn("报修人为空，equipmentId={}", application.getEquipmentId());
                return AjaxResult.error("报修人不能为空");
            }
            
            log.info("新增报修单请求: 设备ID={}, 报修人={}, 故障描述={}", 
                application.getEquipmentId(), application.getReportPerson(), application.getFaultDescription());
            
            boolean success = repairApplicationService.saveRepairApplication(application);
            if (success) {
                log.info("新增报修单成功: 报修人={}", application.getReportPerson());
                return AjaxResult.success("新增成功");
            } else {
                log.error("新增报修单失败: 报修人={}", application.getReportPerson());
                return AjaxResult.error("新增失败");
            }
        } catch (Exception e) {
            log.error("新增报修单失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 修改设备报修单
     */
    @Log(title = "设备报修单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbRepairApplication application)
    {
        try {
            if (repairApplicationService.updateRepairApplication(application)) {
                return AjaxResult.success("修改成功");
            } else {
                return AjaxResult.error("修改失败");
            }
        } catch (Exception e) {
            log.error("修改报修单失败", e);
            return AjaxResult.error("修改失败: " + e.getMessage());
        }
    }

    /**
     * 删除设备报修单
     */
    @Log(title = "设备报修单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        try {
            int successCount = 0;
            for (Integer id : ids) {
                if (repairApplicationService.deleteRepairApplication(id)) {
                    successCount++;
                }
            }
            if (successCount == ids.length) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.success(String.format("删除部分成功，共%d条，成功%d条", ids.length, successCount));
            }
        } catch (Exception e) {
            log.error("删除报修单失败", e);
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取自动生成的报修单编号
     */
    @GetMapping("/getNumber")
    public AjaxResult getNumber()
    {
        try {
            return AjaxResult.success(repairApplicationService.generateCode());
        } catch (Exception e) {
            log.error("生成报修单编号失败", e);
            return AjaxResult.error("生成编号失败: " + e.getMessage());
        }
    }
    
    /**
     * 接单处理
     */
    @Log(title = "报修单接单", businessType = BusinessType.UPDATE)
    @PostMapping("/accept")
    public AjaxResult accept(@RequestParam("repair_id") Integer repairId)
    {
        try {
            if (repairApplicationService.acceptRepairApplication(repairId)) {
                return AjaxResult.success("接单成功");
            } else {
                return AjaxResult.error("接单失败");
            }
        } catch (Exception e) {
            log.error("接单失败", e);
            return AjaxResult.error("接单失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消报修单
     */
    @Log(title = "报修单取消", businessType = BusinessType.UPDATE)
    @PostMapping("/cancel")
    public AjaxResult cancel(@RequestParam("repair_id") Integer repairId, @RequestParam("reason") String reason)
    {
        try {
            if (repairApplicationService.cancelRepairApplication(repairId, reason)) {
                return AjaxResult.success("取消成功");
            } else {
                return AjaxResult.error("取消失败");
            }
        } catch (Exception e) {
            log.error("取消报修单失败", e);
            return AjaxResult.error("取消失败: " + e.getMessage());
        }
    }

    /**
     * 获取报修单对应的维修单信息
     */
    @GetMapping("/related-repair-order/{id}")
    public AjaxResult getRelatedRepairOrder(@PathVariable("id") Integer id)
    {
        try {
            // 先获取报修单信息
            SbRepairApplication application = repairApplicationService.getById(id);
            if (application == null) {
                return AjaxResult.error("报修单不存在");
            }
            
            // 获取维修单服务
            ISbRepairOrderService repairOrderService = SpringUtils.getBean(ISbRepairOrderService.class);
            if (repairOrderService != null) {
                // 查找对应的维修单
                SbRepairOrder repairOrder = repairOrderService.selectSbRepairOrderBySourceCode(application.getRepairCode());
                if (repairOrder != null) {
                    return success(repairOrder);
                } else {
                    return AjaxResult.error("未找到对应的维修单");
                }
            } else {
                return AjaxResult.error("获取维修单服务失败");
            }
        } catch (Exception e) {
            log.error("获取关联维修单失败", e);
            return error("获取关联维修单失败: " + e.getMessage());
        }
    }
} 